package com.wangjie.minio.autoconfigure;

import com.wangjie.minio.policy.MinioPolicyLoader;
import com.wangjie.minio.service.MinioService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.SetBucketPolicyArgs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.StringUtils;

/**
 * 自动配置类: 给容器中导入我们经常使用的组件, 该组件的所有参数来源于xxxProperties属性类
 */
@Configuration
// 开启指定类的ConfigurationProperties功能, 此注解有两个作用 1: 将MinioProperties中的所有属性和配置文件进行绑定 2: 将MinioProperties加入到Spring容器中
@EnableConfigurationProperties(MinioProperties.class)
// 只有当类路径中存在MinioClient类时, 才会加载这个配置类
@ConditionalOnClass(MinioClient.class)
// 配置属性为minio.enabled, 当该属性值为true时, 条件成立, 配置生效, 如果配置文件中没有minio.enabled这个属性, 由于matchIfMissing=true, 则条件成立(即默认启用)
@ConditionalOnProperty(prefix = "minio", name = "enabled", havingValue = "true", matchIfMissing = true)
public class MinioAutoConfiguration {
    private static final Logger logger = LoggerFactory.getLogger(MinioAutoConfiguration.class);

    private final MinioProperties properties;

    // 只有一个有参构造器的情况下, 参数的值会自动从容器中获取
    public MinioAutoConfiguration(MinioProperties properties) {
        this.properties = properties;
    }

    @Bean
    // 只有当Spring容器中不存在指定类型的Bean时, 才会创建这个Bean
    @ConditionalOnMissingBean
    public MinioClient minioClient(MinioPolicyLoader minioPolicyLoader) throws Exception {
        logger.info("Initializing MinIO client");
        // 创建MinioClient
        MinioClient minioClient = MinioClient.builder()
                .endpoint(properties.getEndpoint())
                .credentials(properties.getAccessKey(), properties.getSecretKey())
                .build();
        initializeBucket(minioClient, minioPolicyLoader);
        return minioClient;
    }

    private void initializeBucket(MinioClient minioClient, MinioPolicyLoader minioPolicyLoader) throws Exception {
        String bucketName = properties.getBucketName();
        if (bucketName == null || bucketName.isEmpty()) {
            logger.warn("No bucket name configured. Skipping bucket initialization.");
            return;
        }
        // 判断桶是否存在, 如果不存在则创建
        boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (exists) {
            logger.info("Bucket {} already exists.", bucketName);
            return;
        }

        logger.info("Creating bucket {}", bucketName);
        minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        logger.info("Bucket {} created.", bucketName);
        // 设置桶访问权限
        String policy = minioPolicyLoader.loadPolicy(bucketName);
        if (StringUtils.hasText(policy)) {
            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder()
                    .bucket(bucketName)
                    .config(policy)
                    .build());
            logger.info("Bucket policy applied to {}", bucketName);
        }
    }

    @Bean
    @ConditionalOnMissingBean
    public MinioService minioService(MinioClient minioClient, MinioProperties minioProperties) {
        return new MinioService(minioClient, minioProperties);
    }

    @Bean
    @ConditionalOnMissingBean
    public MinioPolicyLoader minioPolicyLoader(ResourceLoader resourceLoader) {
        return new MinioPolicyLoader(resourceLoader);
    }
}
